package com.zp.mvppractice.utils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Date;
import java.util.Locale;

import okhttp3.FormBody;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * Created by izp on 2017/5/8.
 */

public class StringUtils {
    public static String getRequestString(Request request, long t1, long date1){

        String method=request.method();
        if ("POST".equals(method)) {
            StringBuilder params = new StringBuilder();
            if (request.body() instanceof FormBody) {
                FormBody body = (FormBody) request.body();
                for (int i = 0; i < body.size(); i++) {
                    params.append(body.encodedName(i)).append("=").append(body.encodedValue(i)).append(",");
                }
                params.delete(params.length() - 1, params.length());//减去最后一个逗号么？
                return String.format(Locale.CHINA,"发送请求：[%s] %n 时间：[%tc] %n 精确时间：[%d] %n 请求头：[%s] %n 请求参数：[%s]",
                        request.toString(),new Date(date1),t1,request.headers(),params);
            }
        }
        return String.format(Locale.CHINA,"发送请求：%s %n 时间：%tc %n 精确时间：%d %n 请求头：%s ",
                request.toString(),new Date(date1),t1,request.headers());
    }

    public static String getResponseString(Response response, long t1, long date1) throws IOException {
        long t2 = System.nanoTime();//收到响应的时间,提供相对精确的计时，但是不能用他来计算当前日期
        long date2 = System.currentTimeMillis();//获取响应的时间点
//                    KLog.v(response.body().string());

        ResponseBody responseBody = response.peekBody(1024 * 1024);
        String jsonString=responseBody.string();
//        ISO-8859-1,GBK utf-8
//        String json = new String(jsonString.getBytes("GBK"),"utf-8");
        try {
            jsonString =new JSONObject(jsonString).toString();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return String.format(Locale.CHINA,"接收响应： [%s] %n 响应体：{%s} %n 响应时间：[%tc] %n 精确时间差：[%.1fms] %n 响应头：[%s]",
                response.toString(),
                jsonString,
                new Date(date2),
                (t2 - t1) / 1e6d,
                response.headers()
        );
    }
}
